package com.yoo.ons.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.view.GestureDetector
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.lifecycle.ViewModelProvider
import com.yoo.module_base.R
import com.yoo.module_base.base.BaseDialogFragment
import com.yoo.module_base.utils.ScreenUtils
import com.yoo.module_base.utils.log
import com.yoo.module_base.utils.setOnClickCallback
import com.yoo.ons.databinding.DialogFragmentTopBinding
import com.yoo.ons.dialog.viewmodel.ProInfoDialogViewModel
import com.yoo.ons.function.me.viewmodel.MeViewModel
import com.yoo.ons.util.dpToPx
import com.yoo.ons.util.screenHeight

/**
 * 最顶部的Top弹窗添加yigeView
 * 1、控制点击最小化信息弹窗 2、控制触摸滑动去切换banner
 */
class ProInfoTopDialogFragment : BaseDialogFragment() {
    private var innerBinding: DialogFragmentTopBinding? = null
    private val binding get() = innerBinding!!
    private val proInfoViewModel by lazy {
        ViewModelProvider(requireActivity())[ProInfoDialogViewModel::class.java]
    }
    private val meViewModel by lazy {
        ViewModelProvider(requireActivity())[MeViewModel::class.java]
    }
    private var gestureDetector: GestureDetector? = null
    private var isScrollingUp = false
    private var isScrollingDown = false
    private var isTouchDown = false
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.window?.setFlags(
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
        )
        dialog.window?.setFlags(
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        )
        return dialog
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding = innerBinding
            ?: DialogFragmentTopBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun setWindow(win: Window) {
        win.setWindowAnimations(R.style.DialogAnimation)
        win.decorView.setPadding(0, 0, 0, 0)
        val lp = win.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        win.attributes = lp
        win.setGravity(Gravity.TOP)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 设置 View 的高度为屏幕高度的一半
        val layoutParams = binding.vProfileInfoTop.layoutParams
        layoutParams.height = screenHeight() / 2
        binding.vProfileInfoTop.layoutParams = layoutParams

        //动态设置返回键距离上边边距 = 状态栏+4dp
        val statusHeight = ScreenUtils.getStatusBarHeight(context)
        val imgBackLayoutParams =
            binding.imgProfileInfoBack.layoutParams as ViewGroup.MarginLayoutParams
        imgBackLayoutParams.setMargins(0, statusHeight - dpToPx(12), 0, 0)
        binding.imgProfileInfoBack.layoutParams = imgBackLayoutParams

        // 创建 GestureDetector
        gestureDetector =
            GestureDetector(requireActivity(), object : GestureDetector.SimpleOnGestureListener() {
                override fun onDown(e: MotionEvent): Boolean {
                    // 重置滚动标志
                    isScrollingUp = false
                    isScrollingDown = false
                    // 处理按下事件
                    log("ProInfoTopDialogFragment onDown isScrollingUp=${this@ProInfoTopDialogFragment.isScrollingUp}  isScrollingDown=${this@ProInfoTopDialogFragment.isScrollingDown}")
                    //点击缩小信息弹窗高度到五分之一
                    if (!isTouchDown) {
                        isTouchDown = true
                        proInfoViewModel.showProfileInfoMinHeight(true)
                        //将view高度修改，使其滑动banner区域更大
                        val layoutParams2 = binding.vProfileInfoTop.layoutParams
                        layoutParams2.height = (screenHeight() / 1.5).toInt()
                        binding.vProfileInfoTop.layoutParams = layoutParams2
                    }
                    return true
                }

                override fun onScroll(
                    e1: MotionEvent?,
                    e2: MotionEvent,
                    distanceX: Float,
                    distanceY: Float
                ): Boolean {
                    // 处理滑动事件
                    if (distanceY > 0) {
                        // 向上滑动 切换下一个banner图片 避免重复调用好几遍需要去重只让触发一遍
                        log("ProInfoTopDialogFragment onScroll up  isScrollingUp=${this@ProInfoTopDialogFragment.isScrollingUp}  isScrollingDown=${this@ProInfoTopDialogFragment.isScrollingDown}")
                        if (!isScrollingUp) {
                            isScrollingUp = true
                            isScrollingDown = false
                            proInfoViewModel.switchBanner(0)
                        }
                    } else {
                        // 向下滑动 切换上一个banner图片
                        log("ProInfoTopDialogFragment onScroll down  isScrollingUp=${this@ProInfoTopDialogFragment.isScrollingUp}  isScrollingDown=${this@ProInfoTopDialogFragment.isScrollingDown}")
                        if (!isScrollingDown) {
                            isScrollingDown = true
                            isScrollingUp = false
                            proInfoViewModel.switchBanner(1)
                        }
                    }
                    return true
                }

                override fun onSingleTapUp(e: MotionEvent): Boolean {
                    // 处理松开事件
                    log("ProInfoTopDialogFragment onSingleTapUp  isScrollingUp=${this@ProInfoTopDialogFragment.isScrollingUp}  isScrollingDown=${this@ProInfoTopDialogFragment.isScrollingDown}")
                    return true
                }
            })
        // 设置view的OnTouchListener
        binding.vProfileInfoTop.setOnTouchListener { v, event ->
            gestureDetector?.onTouchEvent(event) == true
        }

        proInfoViewModel.slideShowTopViewLiveData.observe(viewLifecycleOwner) {
            log("ProInfoTopDialogFragment slideShowTopViewLiveData $it")
            if (it) {
                binding.vProfileInfoTop.visibility = View.VISIBLE
            } else {
                binding.vProfileInfoTop.visibility = View.GONE
            }
        }

        binding.imgProfileInfoBack.setOnClickCallback {
            //点击返回按钮
            meViewModel.closeProfileDialog(true)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        log("ProInfoTopDialogFragment onDestroyView")
        //重新需要release这些livedata
        proInfoViewModel.showProfileInfoMinHeight(false)
        proInfoViewModel.switchBanner(-1)
        isScrollingUp = false
        isScrollingDown = false
        isTouchDown = false
        innerBinding = null
        dismissAllowingStateLoss()
    }

    companion object {
        fun newInstance(): ProInfoTopDialogFragment {
            return ProInfoTopDialogFragment()
        }
    }
}